package com.example.minesweepers;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class OptionsActivity extends Activity implements OnClickListener {
	private static String defaultName;
	private static final int SMALL_SIZE_BOARD = 5;
	private static final String DEFAULT_PLAYER_NAME = "Player";
	private TextView playerName; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_options);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		defaultName = getSavedName();
		
		playerName = (TextView) findViewById(R.id.editName);
		if(defaultName != null && !defaultName.equals(""))
			playerName.setText(defaultName);

		addButton(R.id.smallSizeButton);
		addButton(R.id.largeSizeButton);
		addButton(R.id.mediumSizeButton);
	}

	private String getSavedName() {
		SharedPreferences settings = getPreferences(MODE_PRIVATE);
		return settings.getString("name", "");	
	}

	private String getPlayerName() {
		String playerN = playerName.getText().toString();
		return playerN == null || playerN.equals("") ?
				DEFAULT_PLAYER_NAME : playerN;
	}

	private void addButton(int id) {
		Button newGameButton = (Button) findViewById(id);
		newGameButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		Intent startingGameSizeIntent = new Intent(OptionsActivity.this, GameActivity.class);
		switch (v.getId()) {
		case R.id.smallSizeButton:
			startingGameSizeIntent.putExtra("size", SMALL_SIZE_BOARD);
			break;
		case R.id.mediumSizeButton:
			startingGameSizeIntent.putExtra("size", SMALL_SIZE_BOARD * 2);
			break;
		case R.id.largeSizeButton:
			startingGameSizeIntent.putExtra("size", SMALL_SIZE_BOARD * 3);
			break;
		default:
			break;
		}
		saveName();
		startingGameSizeIntent.putExtra("name", getPlayerName());
		startActivity(startingGameSizeIntent);
	}

	private void saveName() {
		SharedPreferences settings = getPreferences(MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("name", getPlayerName());
		editor.commit();
	}
}